﻿using RockBus.Monitoring.DataContracts;
using RockBus.Monitoring.DataContracts.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RockBus.Monitoring
{
    public class PerformanceCounterCategoryCollector : PerformanceCounterCollectorBase
    {
        public PerformanceCounterCategoryCollector(PerformanceCounterCategoryConfiguration pcc, int bufferSize)
            : base(pcc, bufferSize)
        {
        }

        public override void Collect()
        {
            var pcc = new System.Diagnostics.PerformanceCounterCategory(this.PerformanceCounterConfigurationBase.CategoryName);
            var idcc = pcc.ReadCategory();

            if ((null == idcc) || (idcc.Count == 0))
            {
                return;
            }

            // Set new values
            var keys = new HashSet<Tuple<string, string>>();
            foreach (InstanceDataCollection currentInstanceDataCollection in idcc.Values)
            {
                foreach (InstanceData currentInstanceData in currentInstanceDataCollection.Values)
                {
                    keys.Add(new Tuple<string, string>(currentInstanceDataCollection.CounterName, currentInstanceData.InstanceName));
                    this.AddCounterSample(currentInstanceDataCollection.CounterName, currentInstanceData.InstanceName, currentInstanceData.Sample);
                }
            }

            // Remove stale instances
            foreach (var key in this.RoundRobinBufferDictionary.Keys.ToArray())
            {
                if (!keys.Contains(key))
                {
                    Tuple<PerformanceCounterInstance, RoundRobinBuffer> entry = null;
                    this.RoundRobinBufferDictionary.TryRemove(key, out entry);
                }
            }
        }
    }
}
